<template>
    <div class="person-center">
        <a-tabs v-model:activeKey="activeKey" :tab-position="tabPosition">
            <a-tab-pane key="3" tab="用户信息">
                <div class="top-title">
                    <span>用户信息</span>
                </div>
                <div class="user-info-content">
                    <a-form class="user-info" ref="formRef1" :model="formState" :rules="rulesUserInfo"
                        :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-form-item ref="name" label="用户名" name="userName">
                            <a-input v-model:value="formState.userName" disabled />
                        </a-form-item>
                        <a-form-item ref="name" label="昵称" name="nickName">
                            <a-input v-model:value="formState.nickName" />
                        </a-form-item>
                        <a-form-item label="性别" name="sex">
                            <a-radio-group v-model:value="formState.sex">
                                <a-radio :value="0">男</a-radio>
                                <a-radio :value="1">女</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="备注" name="remark">
                            <a-textarea :rows="4" v-model:value="formState.remark" />
                        </a-form-item>
                        <a-form-item>
                            <a-button class="submit-btn" type="primary" @click="handleSaveUserInfo()">保存</a-button>
                        </a-form-item>
                    </a-form>
                    <!-- 头像区域 -->
                    <div class="user-avatar">
                        <a-upload name="avatar" v-model:file-list="fileList" :show-upload-list="false"
                            :before-upload="beforeUpload" class="avatar-uploader" :customRequest="customRequest">
                            <!-- 头像容器 -->
                            <div class="avatar-wrapper">
                                <img :src="formState.avatar" class="avatar-img" alt="用户头像">
                                <!-- 遮罩层 -->
                                <div class="avatar-mask">
                                    <PlusOutlined class="plus-icon" />
                                </div>
                            </div>
                        </a-upload>
                    </div>
                </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="重置密码">
                <div class="top-title">
                    <span>重置密码</span>
                </div>
                <div class="reset-password">
                    <a-form ref="formRef2" :model="resetPwdForm" :rules="rules" :label-col="labelCol1"
                        :wrapper-col="wrapperCol">
                        <a-form-item ref="password" label="密码" name="password">
                            <a-input-password v-model:value="resetPwdForm.password" />
                        </a-form-item>
                        <a-form-item ref="confirmPassword" label="确认密码" name="confirmPassword">
                            <a-input-password v-model:value="resetPwdForm.confirmPassword" />
                        </a-form-item>
                        <a-form-item>
                            <a-button class="submit-btn" type="primary" @click="handleResetPwd">确定</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script setup>
import { getUserInfo, updatePassword, updateUserInfo, updateAvatar } from "@/api/user";
import { useUserStore } from "@/stores/user";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import { createVNode, onMounted, reactive, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { upload2 } from '@/api/file';
import { baseURL } from '@/utils/request.js';
import axios from "axios";

const router = useRouter();
const userStore = useUserStore();

const activeKey = ref("3");

const fileList = ref([]);

const validatePass = async (_rule, value) => {
    if (value === '') {
        passValidateFlag.value = false;
        return Promise.reject('请输入密码');
    } else {
        if (!validatePassword(value)) {
            passValidateFlag.value = false;
            return Promise.reject('由数字，小写字母，大写字母和字符中的任意二种组成，且长度不小于8位。');
        }
        passValidateFlag.value = true;
        return Promise.resolve();
    }
};
const validatePass2 = async (_rule, value) => {
    if (value === '') {
        passValidateFlag1.value = false;
        return Promise.reject('请再次输入密码');
    } else if (value !== resetPwdForm.password) {
        passValidateFlag1.value = false;
        return Promise.reject("两次输入的密码不一致");
    } else {
        passValidateFlag1.value = true;
        return Promise.resolve();
    }
};

// 屏幕宽度
const windowWidth = ref(window.innerWidth);
// tab 切换位置
const tabPosition = computed(() => {
    return windowWidth.value > 768 ? "left" : "top";
});
// 获取屏幕宽度
const handleScreenResize = () => {
    windowWidth.value = window.innerWidth;
}

const validatePassword = (password) => {
    // 至少8位长度检查
    if (password.length < 8) return false;

    // 定义四种字符类型的正则
    const hasNumber = /\d/.test(password);          // 包含数字
    const hasLower = /[a-z]/.test(password);        // 包含小写字母
    const hasUpper = /[A-Z]/.test(password);        // 包含大写字母
    const hasSpecial = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password); // 包含特殊字符

    // 统计满足的字符类型数量
    const conditionsMet = [hasNumber, hasLower, hasUpper, hasSpecial]
        .filter(Boolean).length;

    // 至少满足两种类型
    return conditionsMet >= 2;
}

const rules = {
    password: [
        {
            required: true,
            validator: validatePass,
            trigger: 'change',
        },
    ],
    confirmPassword: [
        {
            required: true,
            validator: validatePass2,
            trigger: 'change',
        },
    ],
};
const rulesUserInfo = {
    userName: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'change',
        },
    ],
    nickName: [
        {
            required: true,
            message: '昵称不能为空',
            trigger: 'change',
        },
    ],
};

onMounted(() => {
    window.addEventListener("resize", handleScreenResize);

    getUserInfo().then((res) => {
        if (res.code === 200 && res.data) {
            let data = res.data;
            formState.nickName = data.nickName;
            formState.userName = data.userName;
            formState.sex = data.sex;
            formState.remark = data.remark;
            formState.avatar = data.avatar;
        }
    });
})


const wrapperCol = reactive({
    span: 0,
    offset: 0,
});
// 标签宽度
const labelCol = {
    style: {
        width: '65px',
    },
};
const labelCol1 = {
    style: {
        width: '86px',
    },
};

const resetPwdForm = reactive({
    password: "",
    confirmPassword: "",
});

const formState = reactive({
    sex: "",
    remark: "",
    userName: "",
    nickName: "",
});

const formRef1 = ref(null);
const formRef2 = ref(null);

const passValidateFlag = ref(false);
const passValidateFlag1 = ref(false);
// 更新密码
const handleResetPwd = () => {
    try {
        formRef2.value.validateFields();
        if (passValidateFlag.value && passValidateFlag1.value) {
            Modal.confirm({
                title: '确定要修改密码吗？',
                icon: createVNode(ExclamationCircleOutlined),
                content: createVNode(
                    'div',
                    {
                        style: 'color:red;',
                    },
                    '修改后需要重新登录，请牢记新密码',
                ),
                okText: '确定',
                cancelText: '取消',
                onOk() {
                    updatePassword(resetPwdForm).then((res) => {
                        if (res.code === 200) {
                            localStorage.removeItem('userName');
                            localStorage.removeItem('avatar');
                            localStorage.removeItem('nickName');
                            localStorage.removeItem('password');
                            localStorage.removeItem('remember');
                            localStorage.removeItem('token');
                            message.success('修改密码成功，请重新登录');
                            router.push("/login");
                        }
                    });
                },
                onCancel() {
                },
                class: 'updatePwd',
            });
        }
    } catch (error) { }
}
// 保存用户信息
const handleSaveUserInfo = () => {
    updateUserInfo(formState).then((res) => {
        if (res.code === 200) {
            message.success("保存成功");
            userStore.setNickName(formState.nickName);
            localStorage.setItem('nickName', formState.nickName);
        }
    });
}

// 头像上传前校验
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式的图片!');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 52;
    if (!isLt2M) {
        message.error('图片大小不能超过5MB!');
        return false;
    }
    return true;
};

// 上传文件
const customRequest = async ({ file }) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('moduleId', 3);

    const res = await axios.post(
        baseURL + 'lzh/file/upload2',
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data',
                'token': localStorage.getItem('token'),
            },
        }
    );

    const fileInfo = res.data.data;
    if (res.data.code !== 200 || !fileInfo) {
        message.success("上传失败");
        return
    }

    await updateAvatar({ url: fileInfo.fileAddress }).then((res) => {
        if (res.code === 200) {
            message.success("上传成功");
            localStorage.setItem('avatar', fileInfo.fileAddress);
            userStore.setAvatar(fileInfo.fileAddress);
            formState.avatar = fileInfo.fileAddress;
        }
    }).catch(error => { })
};
</script>

<style scoped lang="less">
.person-center {
    /* 上浅蓝下白的渐变，与蓝色内容呼应 */
    // background: linear-gradient(180deg, #f0f7ff 0%, #ffffff 100%);
    width: 100%;
    padding: 20px;
    position: relative;
    min-height: 100vh;
    margin-bottom: -30px;
    padding-top: 100px;

    .top-title {
        border-bottom: 1px solid rgb(230, 227, 227);
        display: flex;
        height: 50px;
        align-items: center;
        padding-left: 15px;
        margin-bottom: 10px;
        font-weight: 600;
    }

    .user-info-content {
        padding: 10px;
        display: flex;
        width: 100%;

        @media (max-width: 768px) {
            flex-direction: column-reverse;
        }

        .user-info {
            width: 40%;

            @media (max-width: 768px) {
                width: 100%;
            }
        }

        .user-avatar {
            width: 60%;
            display: flex;
            justify-content: center;
            align-items: center;

            @media (max-width: 768px) {
                width: 100%;
                margin-bottom: 50px;
                padding-top: 50px;
            }

            .avatar-uploader {
                cursor: pointer;

                &:hover {

                    // 鼠标移入时显示遮罩层 - 关键修改
                    .avatar-mask {
                        opacity: 0.7;
                    }

                    // 鼠标移入时图标微动画
                    .plus-icon {
                        transform: scale(1.1);
                    }
                }
            }

            // 头像容器
            .avatar-wrapper {
                position: relative;
                width: 100px;
                height: 100px;
                border-radius: 50%;
                overflow: hidden;
                border: 2px solid #f0f0f0;
            }

            // 头像图片 - 关键修改
            .avatar-img {
                width: 100%;
                height: 100%;
                object-fit: cover; // 保证图片不变形
                transition: filter 0.3s ease;
            }

            // 遮罩层 - 关键修改
            .avatar-mask {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0; // 默认隐藏
                transition: opacity 0.3s ease;
            }

            // 加号图标
            .plus-icon {
                color: #fff;
                font-size: 24px;
                transition: transform 0.3s ease;
            }
        }
    }

    .reset-password {
        padding: 10px;
        max-width: 1000px;
    }

    .submit-btn {
        @media (max-width: 768px) {
            margin-left: 42.5%;
        }

        @media (min-width: 768px) {
            margin-left: 20px;
        }
    }

    // tab标题栏去除空隙
    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs-left>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane,
    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs-left>div>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane {
        padding-left: 0;
    }
}
</style>